package com.cw.service.impl;

import com.alibaba.excel.EasyExcel;
import com.cw.dto.BizMergeStrategy;
import com.cw.dto.DeptUsedBedReportDTO;
import com.cw.dto.ManageBedCalculationDTO;
import com.cw.dto.RowRangeDto;
import com.cw.dto.WorkSumReportCondition;
import com.cw.dto.WorkSumReportDTO;
import com.cw.entity.CwglBedtypechange;
import com.cw.entity.HisCwglBed;
import com.cw.entity.SysUser;
import com.cw.mapper2.ReportMapper;
import com.cw.request.DataSourceRequest;
import com.cw.response.DataSourceResponse;
import com.cw.response.EmptyBedsResponse;
import com.cw.service.ISysUserService;
import com.cw.service.IThisIiPrepayinService;
import com.cw.service.ReportService;
import com.cw.util.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p></p>
 *
 * @author: ly
 * @date: 2021/06/04 14:39
 **/
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IThisIiPrepayinService thisIiPrepayinService;

    /**
     * 分页查询集管床位计算统计列表
     *
     * @param dataSourceRequest 查询条件
     * @return java.util.List<com.cw.dto.ManageBedCalculationDTO>
     * @author ly
     * @date 2021/6/4 14:38
     */
    @Override
    public PageInfo<ManageBedCalculationDTO> getManageBedCalculationDTO(DataSourceRequest dataSourceRequest) {
        PageHelper.startPage(dataSourceRequest.getPageNum(), dataSourceRequest.getPageSize());
        List<ManageBedCalculationDTO> manageBedCalculationDTO = reportMapper.getManageBedCalculationDTO(dataSourceRequest);
        return new PageInfo<>(manageBedCalculationDTO);
    }

    /**
     * 下载集管床位计算统计excel
     *
     * @param dataSourceRequest 查询条件
     * @param response          响应对象
     * @author ly
     * @date 2021/6/4 16:24
     */
    @Override
    public void getManageBedCalculationDtoExcel(DataSourceRequest dataSourceRequest, HttpServletResponse response) throws IOException {
        List<ManageBedCalculationDTO> manageBedCalculationDTO = reportMapper.getManageBedCalculationDTO(dataSourceRequest);
//        GetBedCalculationSource(manageBedCalculationDTO);
        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        EasyExcel.write(response.getOutputStream(), ManageBedCalculationDTO.class).sheet("sheet").doWrite(manageBedCalculationDTO);
    }

    /**
     * 个人工作量统计
     *
     * @param condition 查询条件
     * @return java.util.List<com.cw.dto.WorkSumReportDTO>
     * @author ly
     * @date 2021/6/15 15:39
     */
    @Override
    public List<WorkSumReportDTO> getWorkSumReportDto(WorkSumReportCondition condition) {
        List<WorkSumReportDTO> workSumReportDto = reportMapper.getWorkSumReportDTO(condition);
        //空指针判断
        if (CollectionUtils.isEmpty(workSumReportDto)) {
            return null;
        }
        //获取不重复的操作人主键集合
        List<String> collect = workSumReportDto.stream().map(WorkSumReportDTO::getOperNo).distinct().collect(Collectors.toList());

        //获取操作人的姓名
        //为什么要单独查询? 因为他们不是一个数据库,理所应当就不能join一个sql写完
        Map<String, String> map = new HashMap<>(6);
        for (String userId : collect) {
            //空指针判断
            if (userId == null) {
                continue;
            }
            SysUser byId = sysUserService.getById(userId);
            map.put(userId, byId.getRealname());
        }
        //根据userId获取真实姓名
        workSumReportDto.parallelStream().forEach(workSumReportDTO -> workSumReportDTO.setOperName(map.get(workSumReportDTO.getOperNo())));
        return workSumReportDto;
    }

    /**
     * 个人工作量统计
     *
     * @param condition 查询条件
     * @author ly
     * @date 2021/6/16 10:19
     */
    @Override
    public void getWorkSumReportDtoExcel(WorkSumReportCondition condition) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        List<WorkSumReportDTO> workSumReportDto = getWorkSumReportDto(condition);
        //空指针判断
        if (CollectionUtils.isEmpty(workSumReportDto)) {
            return;
        }

        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        Map<String, List<RowRangeDto>> map = ExcelUtil.addMerStrategy(workSumReportDto);
        EasyExcel.write(response.getOutputStream(), WorkSumReportDTO.class).registerWriteHandler(new BizMergeStrategy(map)).sheet("sheet").doWrite(workSumReportDto);
    }

    /**
     * 获取科室床位预约统计报表饼图数据
     *
     * @param condition 查询条件
     * @return java.util.List<com.cw.dto.DeptUsedBedReportDTO>
     * @author ly
     * @date 2021/6/18 9:21
     */
    @Override
    public List<DeptUsedBedReportDTO> getDeptUsedBedReportDTO(WorkSumReportCondition condition) {
        return reportMapper.getDeptUsedBedReportDTO(condition);
    }

    /**
     * 获取科室床位预约统计报表饼图数据-导出
     *
     * @param condition 查询条件
     * @author ly
     * @date 2021/6/18 10:30
     */
    @Override
    public void getDeptUsedBedReportDtoExcel(WorkSumReportCondition condition) throws IOException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        List<DeptUsedBedReportDTO> deptUsedBedReportDTO = getDeptUsedBedReportDTO(condition);
        //空指针判断
        if (CollectionUtils.isEmpty(deptUsedBedReportDTO)) {
            return;
        }

        String name = String.valueOf(System.currentTimeMillis());
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx;");
        EasyExcel.write(response.getOutputStream(), DeptUsedBedReportDTO.class).sheet("sheet").doWrite(deptUsedBedReportDTO);
    }
}
